const SCENE_WIDTH = 750;
const SCENE_HEIGHT = 1301;

class Scene {
  /**
   * 场景sprite实例
   *
   * @type {PIXI.Sprite}
   * @memberof Scene
   */
  scene;

  constructor(app, sceneInfo) {
    this.sceneInfo = sceneInfo;
    this.app = app;

    this.create();
  }

  /**
   * 更换场景
   *
   * @param {MatterBasicInfo} sceneInfo
   * @memberof Scene
   */
  change(sceneInfo) {
    if (!this.scene) throw new Error('场景尚未创建，请先添加一个场景吧~');
    this.scene.texture = getTextureFromCache(
      this.app,
      sceneInfo.name,
      sceneInfo.url
    );
  }

  /**
   * 创建一个场景
   *
   * @private
   * @memberof Scene
   */
  create() {
    const { name, url } = this.sceneInfo || {};

    if (!url || !name) {
      return;
    }

    const { screen, stage } = this.app;
    const texture = getTextureFromCache(this.app, name, url); // 优先从预加载缓存中取出
    const sprite = PIXI.Sprite.from(texture);

    // scene渲染根据机型等比缩放，将中心置于screen中心
    const ratio = SCENE_WIDTH / screen.width;
    sprite.width = screen.width;
    sprite.height = SCENE_HEIGHT / ratio;

    if (sprite.height > screen.height) {
      sprite.y = (screen.height - sprite.height) / 2;
    }

    stage.addChild(sprite);
    this.scene = sprite;
  }
}
